

import {vec3,mat4} from 'gl-matrix'
import {toRadius} from "./utils";

export class Camera {

     position: vec3;
     target: { position: [number, number, number] | Float32Array };
     up: vec3;
     viewMatrix: mat4;
     projMatrix: mat4;
     invProjMatrix:mat4 = mat4.create(); // 用于pick

    fovy = 60;
    width = 800;
    height = 600;
    near = 0.1;
    far = 1000;

    constructor(x:number,y:number,z:number) {
        this.position = vec3.fromValues(x,y,z);
        this.target = {
            position:vec3.fromValues(0,0,0)
        };
        this.up = vec3.fromValues(0,1,0);
        this.viewMatrix = mat4.create();
        this.projMatrix = mat4.create();
    }

    updateViewMatrix(){
        mat4.lookAt(this.viewMatrix,this.position,this.target.position,this.up);

    }

    updateProjMatrix(){
        mat4.perspective(this.projMatrix,toRadius(this.fovy),this.width/this.height,this.near,this.far);
    }

    updateMatrix(){
        this.updateProjMatrix();
        this.updateViewMatrix();
        mat4.invert(this.invProjMatrix,this.projMatrix);
    }

    screen_to_clip(x:number,y:number,z:number) {
        let cx = 2 * x / this.width - 1;
        let cy = 1 - 2 * y / this.height;
        return vec3.fromValues(cx,cy,z);
    }

}
